import { fromEvent } from "rxjs";
import { tap, map, bufferTime, filter } from "rxjs/operators";
import { getLogger, ts } from "../utils";

const BATCH_DURATION_MS = 5000;
const MAX_BATCH_SIZE = 5;

const log0 = getLogger("Purpose");
log0("Demonstrating how to batch packages in express delivery industry",
    `batch for ${BATCH_DURATION_MS}ms with max buffer size of ${MAX_BATCH_SIZE}`,
    "Press Space Key to simulate adding a package");

const packages$ = fromEvent(document, "keydown").pipe(map((e, idx) => `package ${idx}`));

packages$.pipe(
    tap(e => console.log(`${e} ready`)),
    bufferTime(BATCH_DURATION_MS, null, MAX_BATCH_SIZE),
    filter(packages => packages.length > 0),
    map((packages, idx) => [idx, packages] as const)
).subscribe(([batchIdx, packages]) => {
    const log = getLogger(`batch ${batchIdx} @ ` + ts());
    log(`${packages.join(", ")}`);
});
